package com.wan.config.interpace;

import cn.hutool.core.date.DateUtil;
import com.wan.util.JwtTokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * token 拦截器
 * @author xzx
 */
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)  {
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)){
            return false;
        }
        boolean b = JwtTokenUtils.verify(token);
        if (b){
            Integer openId = JwtTokenUtils.getOpenId(token);
            Date date = JwtTokenUtils.getExpDate(token);
            String str = DateUtil.format(date,"yyyy-MM-dd HH:mm:ss");
            log.debug("token超时时间===>"+str);
            log.debug("openid===>"+openId);
            return true;
        }else {
           return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
